/**
 * 解析后的身份证类型
 */
export interface ICardInfo {
  sex: number
  birthday: String
}

/**
 * 判断字符串是否为身份证号
 * @param idCard 身份证号
 */
export const checkIdCard = (idCard: string) => {
  return /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])\d{3}(\d|X|x)$/.test(idCard)
}

export const parseIdCard = (idCard: string): ICardInfo => {
  if (checkIdCard(idCard)) {
    let birthday = ''
    if (idCard.length === 15) {
      // 15位身份证号：年份是19XX
      birthday = `19${idCard.substring(6, 8)}-${idCard.substring(8, 10)}-${idCard.substring(10, 12)}`
    } else if (idCard.length === 18) {
      // 18位身份证号：直接提取年份
      birthday = `${idCard.substring(6, 10)}-${idCard.substring(10, 12)}-${idCard.substring(12, 14)}`
    }
    // 后端接收的是时间戳
    birthday = new Date(birthday).getTime()
    // 性别：身份证第17位，奇数为男，偶数为女
    const genderCode = idCard.length === 15 ? idCard.substring(14, 15) : idCard.substring(16, 17)
    const sex = genderCode % 2 === 1 ? 1 : 2
    return {
      sex,
      birthday
    }
  }
}
